<template>
  <div class="p-6">
    <el-form
      :model="login"
      :rules="rules"
      label-width="auto"
      class="max-w-96 text-white"
      ref="ruleFormRef"
    >
      <el-form-item label="原密码" prop="oldPassword" class="w-full">
        <el-input
          v-model="login.oldPassword"
          size="large"
          autocomplete="off"
          placeholder="请输入"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword" class="w-full">
        <el-input
          v-model="login.newPassword"
          size="large"
          autocomplete="off"
          placeholder="请输入"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm()"
          size="large"
          class="mt-6 w-36 ml-auto"
          >修改</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { passwordUpdate } from "@renderer/https/api/user.js";
import { useRouter } from "vue-router";
import { useStoreTemplate } from "@renderer/store/modules/template";
const storeTemplate = useStoreTemplate();
const router = useRouter();

const login = ref({
  oldPassword: "",
  newPassword: "",
});
const rules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "change" }],
  newPassword: [{ required: true, message: "请输入新密码", trigger: "change" }],
};

const ruleFormRef = ref<FormInstance>();

const submitForm = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      console.log("submit!");
      passwordUpdate(login.value)
        .then((res) => {
          ElMessage.success("修改成功");
          storeTemplate.$state.token = null;
          storeTemplate.$state.userInfo = null;
          router.push("/login");
        })
        .catch((err) => {
          ElMessage.error(err.msg);
        });
    } else {
      return false;
    }
  });
};
</script>
